package com.zhouyu.service;

import com.zhouyu.spring.BeanPostProcessor;
import com.zhouyu.spring.Component;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @program: shouxieSpring
 * @author: jzhou
 * @date: 2022-04-18 22:30
 * @version: 1.0
 * @description: beanPostProcessor接口的实现
 **/
@Component
public class ZhouyuBeanPostProcessor implements BeanPostProcessor {
    @Override
    public Object postProcessBeforeInitialization(String beanName, Object bean) {
        if (beanName.equals("userService")){
            System.out.println("ZhouyuBeanPostProcessor.postProcessBeforeInitialization12314125userService");
        }

        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(String beanName, Object bean) {
        if (beanName.equals("userServiceProxy")){
            Object proxyInstance = Proxy.newProxyInstance(bean.getClass().getClassLoader(), bean.getClass().getInterfaces(), new InvocationHandler() {
                @Override
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    System.out.println("proxyInstance 切面逻辑");
                    // 调用实际对象的指定方法
                    return method.invoke(bean,args);
                }
            });
            return proxyInstance;
        }

        return bean;
    }
}
